<template>
  <div style="border: 1px solid #ccc">
    <!-- 工具栏 -->
    <Toolbar
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      style="border-bottom: 1px solid #ccc"
    />
    <!-- 编辑器 -->
    <Editor
      v-model="props.modelValue"
      :defaultConfig="editorConfig"
      @onChange="handleChange"
      @onCreated="handleCreated"
      @onDestroyed="handleDestroyed"
      @onFocus="handleFocus"
      @onBlur="handleBlur"
      @customAlert="customAlert"
      @customPaste="customPaste"
      style="height: 500px"
    />
  </div>
</template>
<script setup lang="ts">
import { onBeforeUnmount, ref, shallowRef } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { fetchUploadFileWithDeal } from "~/api/file/index";
import { useMessage } from "naive-ui";
import type { MessageReactive } from "naive-ui";

const message = useMessage();
type InsertFnType = (url: string, poster: string) => void;

let messageReactive: MessageReactive | null = null;

// 编辑器实例，必须用 shallowRef ，重要！
const editorRef = shallowRef();

// 编辑器配置
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    insertImage: {
      checkImage(src: string) {
        if (src.indexOf("http") !== 0) {
          return "图片网址必须以 http/https 开头";
        }
        return true;
      },
    },
  },
};
//@ts-ignore
editorConfig.MENU_CONF["uploadImage"] = {
  // 自定义选择图片

  async customUpload(file: File, insertFn: InsertFnType) {
    messageReactive = message.loading("上传中...", {
      duration: 0,
    });
    fetchUploadFileWithDeal({
      file,
      sceneType: "md",
    })
      .then((r) => {
        insertFn(r.path, "alt");
      })
      .finally(() => {
        messageReactive?.destroy();
        messageReactive = null;
      });
  },
};
//@ts-ignore
editorConfig.MENU_CONF["uploadVideo"] = {
  // 自定义上传
  async customUpload(file: File, insertFn: InsertFnType) {
    // TS 语法
    messageReactive = message.loading("上传中...", {
      duration: 0,
    });
    // JS 语法
    fetchUploadFileWithDeal({
      file,
      sceneType: "md",
    })
      .then((r) => {
        insertFn(r.path, "alt");
      })
      .finally(() => {
        messageReactive?.destroy();
        messageReactive = null;
      });
  },
};

// 工具栏配置
const toolbarConfig = {};

// 编辑器回调函数
const handleCreated = (editor: any) => {
  // console.log("created", editor);

  editorRef.value = editor; // 记录 editor 实例，重要！

  // window.editor = editor // 临时测试使用，用完删除
};
interface Props {
  modelValue: string;
}
const props = withDefaults(defineProps<Props>(), {
  modelValue: "",
});
const emits = defineEmits(["update:modelValue"]);
const handleChange = (editor: any) => {
  // console.log("change:", editor.children);
  // const reg = /(?<=((img|source)[^>]*src="))[^"]*/g;
  const htmlStr = editor.getHtml();
  emits("update:modelValue", htmlStr);
};
const handleDestroyed = (editor: any) => {
  // console.log("destroyed", editor);
};
const handleFocus = (editor: any) => {
  // console.log("focus", editor);
};
const handleBlur = (editor: any) => {
  // console.log("blur", editor);
};
const customAlert = () => {
  // alert(`【自定义提示】${type} - ${info}`);
};
const customPaste = (editor: any, event: Event, callback: Function) => {
  callback(true); // 返回 true ，继续默认的粘贴行为
};

// 及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;

  // 销毁，并移除 editor
  editor.destroy();
});

const getHtml = () => {
  const editor = editorRef.value;
  if (editor == null) return;
};
</script>

<style src="@wangeditor/editor/dist/css/style.css"></style>
<style lang="scss">
video {
  width: 100%;
}
.w-e-toolbar,
.w-e-text-container {
  border: none;
  background: var(--layout-background);
  border-radius: 12px !important;
  &::-webkit-scrollbar {
    display: none;
  }
}
.w-e-full-screen-container {
  z-index: 999 !important;
}
</style>
